﻿$(document).ready(function () {

    var missingmap;
    var marker;
    var markersArray = [];

    /// Load notifications on page load
    if ($('#nav-subtab-3c').is(':checked')) {
        loadNotifications();
    }

    $('.nav-subtab-ctrl').click(function () {

        /// Load testimonials
        if ($('#nav-subtab-3c').is(':checked')) {
            loadNotifications();

        } else if ($('#nav-subtab-2c').is(':checked')) { /// Add new testimonial
            $('#nav-sendtestimonial').click(function (e) {
                $('#info').html("We really appreciate your feedback. Feel free to contact us on <a style='color: #fff; text-decoration: none;' href='mailto:uclgadgeteer@gmail.com'>uclgadgeteer@gmail.com</a> or use the form below to leave your feedback.");
                postTestimonial(e);
            });
        }
    });

    function postTestimonial(e) {

        e.preventDefault();

        resetValidation();

        if (!validate()) {
            return false;
        }

        var email = $('#email').val();
        var fullname = $('#fullname').val();
        var message = $('#message').val();
        var subject = $('#subject').val();
        var datetime = new Date().getTime();
        var formatDateTime = "\/Date(" + datetime + ")\/";

        var args = { "Email": email, "Fullname": fullname, "Message": message, "Subject": subject, "Time": formatDateTime };

        $.ajax({
            type: "POST",
            //async: false,
            url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/testimonial",
            data: JSON.stringify(args),
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                console.log("response");
                console.log(response);
                $('#info').show();
                $('#info').html('Your feedback has been successfully sent.');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                $('#info').html('An error occurred while trying to send your message. Try again later.');

                console.log(jqXHR.status);
                console.log(textStatus);
                console.log(errorThrown);

                console.log("ARGS: %s", JSON.stringify(args));
            }
        });
    }

    function loadNotifications() {

        $('#notifications-list').html('');

        var notifications = $.ajax({
            type: 'GET',
            url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/notifications/" + getUserID(),
            contentType: "application/json; charset=utf-8",
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;

        var objNotifications = jQuery.parseJSON(notifications);

        //console.log(objNotifications);
        // return;

        if (objNotifications == "") {
            $("#notificationsInfo").html("There are no notifications messages at this time.");
            $("#notificationsInfo").fadeIn(1000);
        } else {

            $.each(objNotifications, function (i, notifications) {
                var notificationsHTML = "";
                if (notifications.reason == "lost") {
                    notificationsHTML += "<blockquote id='notificationID-" + notifications.notificationId + "' class='notification lost'>";
                } else if (notifications.reason == "triggered") {
                    notificationsHTML += "<blockquote  id='notificationID-" + notifications.notificationId + "'class='notification triggered'>";
                } else if (notifications.reason == "upper_limit_triggered") {
                    notificationsHTML += "<blockquote  id='notificationID-" + notifications.notificationId + "'class='notification upper_limit_triggered'>";
                } else if (notifications.reason == "lower_limit_triggered") {
                    notificationsHTML += "<blockquote id='notificationID-" + notifications.notificationId + "' class='notification lower_limit_triggered'>";
                }

                notificationsHTML += "<p>" + "Your Device '" + notifications.deviceName + "' with ID: " + notifications.deviceId + " has sent a notification. Reason: " + notifications.reason + "</p>";
                //notificationsHTML += "<p>" + "Device ID: " + notifications.deviceId + ", Device Name: " + notifications.deviceName + ", Reason: " + notifications.reason + "</p>";
                notificationsHTML += "<div class='one'>";
                notificationsHTML += "<div id='deleteNotification-" + notifications.notificationId + "' class='deleteNotification solid-red light-text' style='height:35px; line-height:35px; width:70px; padding:1%; font-size:14px;cursor:pointer;font-family: Trebuchet, Arial, sans-serif;'>Remove</div>";
                notificationsHTML += "</div>";

                if (notifications.reason == "lost") {
                    notificationsHTML += "<div class='two'>";
                    notificationsHTML += "<div id='viewOnMapNotification-" + notifications.notificationId + "' deviceid='" + notifications.deviceId + "'" + "sensorid='" + notifications.sensorId + "' class='viewonMapNotification solid-orange light-text' style='height:35px; width:70px; padding:1%; font-size:14px;cursor:pointer;font-family: Trebuchet, Arial, sans-serif;'>View on the Map</div>";
                    notificationsHTML += "</div>";
                }
                notificationsHTML += "</blockquote>";

                $('#notifications-list').append(notificationsHTML);
            });
        }
    }

    $(".deleteNotification").live("click", function () {

        var notification = $(this).attr("id");
        var tokens = notification.split("-");
        var notificationID = tokens[1];
        console.log("notificaitionID: " + notificationID);


        $.ajax({
            type: 'GET',
            url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/notifications/delete/" + notificationID,
            contentType: "application/json; charset=utf-8",
            global: false,
            async: false,
            success: function (data) {
                console.log(data);
                if (data) {
                    $('#notificationID-' + notificationID).fadeOut("slow");
                } else {
                    $("#notificationsInfo").html("An error occurred while trying to remove notification. You may try again");
                    $("#notificationsInfo").fadeIn(1000);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                $("#user").css("outline", "3px solid rgb(235, 46, 46)");
                $("#loginForm").css("outline", "3px solid rgb(235, 46, 46)");
                console.log(jqXHR.status);
                console.log(textStatus);
                console.log(errorThrown);

                console.log("ARGS: NotificationID: ", notificationID);
            }
        });
    });


    $(".viewonMapNotification").live("click", function () {

        $('#nav-subtab-2c').prop('checked', true);

        var sensorID = $(this).attr("sensorid");
        var deviceID = $(this).attr("deviceid");

        console.log("deviceID: " + deviceID);
        console.log("sensorID: " + sensorID);
        /// Fix google map size
        google.maps.event.trigger(missingmap, 'resize');
        $("#lostInfo").fadeIn(1000);
        $("#lostInfo").html("Your Device: " + deviceID + " is now being tracked by our monitoring system. You will be able to monitor your device on the map soon.");

        
        //for (var i = 0; i < 10; i++) {
        //    setTimeout(function () {
        //        var lat = 51.52436;
        //        var lng = 0.13447;
                
               
        //       // lat = lat + (i * 1235);
        //        //lat += lat + (i * 1235);
               
        //    }, 1300);
        //}
       
        /// Update Map Zoom Level
        

        var pusherConfig = pusherConfiguration(sensorID);
        var config = jQuery.parseJSON(pusherConfig);
        console.log(config);

        Pusher.log = function (message) {
            if (window.console && window.console.log) {
                window.console.log(message);
            }
        };

        var pusher = new Pusher(config.Key);
        var channel = pusher.subscribe(config.Channel); //channel 
        channel.bind(config.Event, function (data) { //event 
            console.log(data);

            var obj = jQuery.parseJSON(data);

            for (var i = 0; i < obj.data.length; i++) {
                var lat = obj.data[i].latitude;
                var lng = obj.data[i].longitude;
                console.log("Lat: " + lat + ", Lng: " + lng);

                updateMap(lat, lng);
            }
           
          
            
        });


    });

    function updateMap(lat, lng) {

        // var lat = "51.52436";
        //   var lng = "-0.13447";


        var gpsLocations = new google.maps.LatLng(lat, lng);
        missingmap.panTo(gpsLocations);
        missingmap.setZoom(20);

        marker = new google.maps.Marker({
            position: gpsLocations,
            map: missingmap,
            icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png'
        });

        markersArray.push(marker);
    }


    /// Get USER ID
    function getUserID() {
        var userID = $.ajax({
            type: 'GET',
            url: "scripts/GetSessions.aspx",
            data: { "UserId": "true" },
            dataType: 'html',
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;

        return userID;
    }

    function loadDeviceList() {
        var devices = $.ajax({
            type: 'GET',
            url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/devices/list?userid=" + getUserID() + "&privacy=all",
            contentType: "application/json; charset=utf-8",
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;

        var obj = jQuery.parseJSON(devices);

        if (obj.ErrorDetail == "No device exists for this user") {
            return "401"; // No Device Found
        } else {
            return devices;
        }
    }

    function loadSensorList(deviceID) {
        var sensors = $.ajax({
            type: 'GET',
            url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/sensors?deviceid=" + deviceID,
            contentType: "application/json; charset=utf-8",
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;

        var obj = jQuery.parseJSON(sensors);

        console.log(obj);
       
        if (obj.ErrorDetail == "Retrieval Failed.Nullable object must have a value."
            || obj.ErrorDetail == "There no sensors associated with this Device") {
            $('#settingsInfo').fadeIn(1000);
            $('#settingsInfo').removeClass('solid-purple').addClass('solid-red');
            $('#settingsInfo').html('There are no sensors associated with this device. Either register one or choose another device from the available ones.');
            $('#row-sensors').hide();
            // return false;
        } else {
            $('#info').hide();
            return sensors;
        }
    }

    var devicelist = loadDeviceList();
    var devices = $.parseJSON(devicelist);
    var deviceListDropDown;

    deviceListDropDown = "<option value='-1'>-Any-</option>";
    $.each(devices, function (i, devicelist) {
        deviceListDropDown += "<option value='" + devicelist.response.Id + "'>" + devicelist.response.Name + "</option>";
    });

    $('#device-list').html(deviceListDropDown);


    $('#device-list').change(function () {

        var deviceId = $(this).val();
        console.log("device id: " + deviceId);
        if (deviceId == -1) {
            $('#settingsInfo').hide();
            $('#row-sensors').hide();
            $('#row-loadTrigger').hide();
            $('#row-triggerFields').hide();
            return false;
        }

        var sensorlist = loadSensorList(deviceId);
        var sensors = $.parseJSON(sensorlist);
        var sensorsListDropDown;

        sensorsListDropDown = "<option value='-1'>-Any-</option>";
        $.each(sensors, function (i, sensorlist) {
            sensorsListDropDown += "<option type='" + sensorlist.Sensorid.Type + "' value='" + sensorlist.Sensorid.Id + "'>" + sensorlist.Sensorid.Name + "</option>";
        });

        $('#sensor-list').html(sensorsListDropDown);
        $('#row-sensors').fadeIn(1000);

    });


    $('#sensor-list').change(function () {

        var sensorId = $(this).val();
        $('#settingsInfo').hide();
        if (sensorId == -1) {
            $('#row-loadTrigger').hide();
            $('#row-triggerFields').hide();
            return false;
        }
        $('#row-triggerFields').fadeIn(1000);
        $('#row-loadTrigger').fadeIn(1000);
    });


    /// Set the trigger
    $('#btnLoadTrigger').click(function (e) {
        e.preventDefault();

        var sensorId = $('#sensor-list option:selected').val();
        console.log(sensorId);
        var args = new Object();


        args.LowerLimit = $('#lowerLimit').val();
        args.Name = $('#keyName').val();
        args.UpperLimit = $('#upperLimit').val();
        

        console.log(args);

        var setTrigger = $.ajax({
            type: 'POST',
            url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/sensor/" + sensorId + "/trigger",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(args),
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;


        var obj = jQuery.parseJSON(setTrigger);
        if (obj != "Success") {
            $('#settingsInfo').fadeIn(1000);
            $('#settingsInfo').html("An error occurred while trying to set the trigger. You may try again later");
        } else {
            $('#settingsInfo').fadeIn(1000);
            $('#settingsInfo').html("The trigger has been successfully set for the selected sensor");
        }
        console.log(setTrigger);
        console.log(obj);
    });


    /// Lost Devices on Map

    $('.nav-subtab-ctrl').click(function () {

        /// Load All Devices on Map

        /// Load Missing Devices
        if ($('#nav-subtab-2c').is(':checked')) {


            /// Fix google map size
            google.maps.event.trigger(missingmap, 'resize');

            // $('#discovery-loading').html('This section shows the missing devices');

            //var missingdevices = $.ajax({
            //    type: 'GET',
            //    url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/lostdevices/" + getUserID(),
            //    contentType: "application/json; charset=utf-8",
            //    global: false,
            //    async: false,
            //    success: function (data) {
            //        return data;
            //    }
            //}).responseText;

            //var objMissing = jQuery.parseJSON(missingdevices);
            //console.log(objMissing);
            //if (objMissing == "") {
            //    $('#discovery-loading').fadeIn(1000);
            //    $('#discovery-loading').addClass('solid-red');
            //    $('#discovery-loading').html('No missing devices found');

            //} else {
            //    var missingDevicesListHTML = "";

            //    missingDevicesListHTML = "<option value='-1'>-Any-</option>";
            //    $.each(objMissing, function (i, missingdevices) {
            //        missingDevicesListHTML += "<option type='" + missingdevices.reason + "' value='" + missingdevices.deviceId + "'>" + missingdevices.deviceName + "</option>";
            //    });

            //    $('#missingDevices-list').html(missingDevicesListHTML);
            //}
        }
    });

    //$('#missingDevices-list').change(function () {

    //    var deviceId = $(this).val();
    //    console.log("device id: " + deviceId);
    //    if (deviceId == -1) {
    //        return false;
    //    }

    //    $('#btnLoadMissingMap').fadeIn(1000);
    //    $('#discovery-loading').fadeIn(1000);
    //    $('#discovery-loading').addClass('solid-purple');
    //    $('#discovery-loading').html('You choose to track device:' + $('#missingDevices-list option:selected').text() + ". Reason: " + $('#missingDevices-list option:selected').attr('type') +
    //        '<br />' + 'Click on Track button to start monitoring your device');
    //});

    function initializeMissingMap() {

        var myLatlngMissing = new google.maps.LatLng(51.524362, -0.134475);
        var mapOptionsMissing = {
            zoom: 2,
            center: myLatlngMissing,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        missingmap = new google.maps.Map(document.getElementById('map-missingdevices'), mapOptionsMissing);
        console.log(missingmap);
    }
    google.maps.event.addDomListener(window, 'load', initializeMissingMap);

    //$('#btnLoadMissingMap').click(function () {
    //    alert('Register pusher');

    //    var pusherConfig = pusherConfiguration();
    //    var config = jQuery.parseJSON(pusherConfig);
    //    console.log(config);

    //    Pusher.log = function (message) {
    //        if (window.console && window.console.log) {
    //            //  window.console.log(message);
    //        }
    //    };

    //    var pusher = new Pusher(config.Key);
    //    var channel = pusher.subscribe(config.Channel); //channel 
    //    channel.bind(config.Event, function (livedata) { //event 

    //    });
    //});

    function pusherConfiguration(sensorID) {

        var pusherConfiguration = $.ajax({
            type: 'GET',
            url: "http://uclwebservicetest.cloudapp.net/Services/users.svc/subscribe?sensorid=" + sensorID + "&userid=" + getUserID(),
            contentType: "application/json; charset=utf-8",
            global: false,
            async: false,
            success: function (data) {
                return data;
            }
        }).responseText;
        return pusherConfiguration;
    }
});